package com.eightbears.beboy.ui.merchant.activity;

import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.Spanned;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.CalendarAdapter;
import com.eightbears.beboy.adapter.ValidRecordByDayAdapter;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.util.CommonUtils;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.SpecialCalendar;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.layout.MyLinearLayoutManager;
import com.eightbears.beboy.base.view.layout.ScrollableLayout;
import com.eightbears.beboy.entity.OrderEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.nineoldandroids.view.ViewHelper;
import com.socks.library.KLog;

import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.URL_GETSHOPMAELRCODE;


/**
 * 验证记录页面
 */

public class ValidRecordActivity extends BaseActivity implements GestureDetector.OnGestureListener {

    @BindView(R.id.sw_shopdetail)
    SwipeBackLayout sw_shopdetail;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.gv_calender)
    GridView gv_calender;
    @BindView(R.id.scrollableLayout)
    ScrollableLayout scrollableLayout;
    @BindView(R.id.rl_head)
    RelativeLayout mTopLayout;
    @BindView(R.id.rv_list)
    RecyclerView rv_list;
    @BindView(R.id.view_empty)
    View view_empty;
    @BindView(R.id.tv_count)
    TextView tv_count;
    @BindView(R.id.tv_date)
    TextView tv_date;

    private int currentYear = 0;
    private int currentMonth = 0;
    private int currentDay = 0;
    private float location;
    private String startTime;
    private String endTime;

    private ValidRecordByDayAdapter validRecordByDayAdapter;
    private GestureDetector gestureDetector;
    private CalendarAdapter calendarAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_verification_record);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        tv_title.setText("验证记录");
        initDateInfo();
        initCalendarView();
    }

    @Override
    protected void initData() {
        startTime = CommonUtils.getStartTimeOfDay();
        endTime = CommonUtils.getEndTimeOfDay();
        initAdapter();
        getVerificationRecordData();
    }

    @Override
    protected void initEvent() {
        sw_shopdetail.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
    }

    /**
     * 后退
     */
    @OnClick(R.id.ll_back)
    void back() {
        finish();
    }


    /**
     * 通过网络获取当天验证记录数据
     */
    private void getVerificationRecordData() {
        OkHttpUtils.get().url(URL_GETSHOPMAELRCODE)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("page", "1")
                .addParams("size", "1000")
                .addParams("status", "[1,5]")
                .addParams("shop_id", SPUtil.getUser().getData().getShops().get(0).getShop_id() + "")
                .addParams("start_at", startTime)
                .addParams("end_at", endTime)
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                OrderEntity orderEntity = GsonUtil.fromJson(response, OrderEntity.class);
                if (String.valueOf(orderEntity.getStatus_code()).equals(CONNECTION_STATUS_SUCCESS)) {
                    String repostText = mContext.getString(R.string.text_valid_count);
                    String formatRepostText = String.format(repostText, orderEntity.getData().getList().size()+"");
                    Spanned htmlRequestText = Html.fromHtml(formatRepostText);
                    tv_count.setText(htmlRequestText);

                    if(orderEntity.getData().getList().size() == 0) {
                        view_empty.setVisibility(View.VISIBLE);
                        rv_list.setVisibility(View.GONE);
                    } else {
                        rv_list.setVisibility(View.VISIBLE);
                        view_empty.setVisibility(View.GONE);
                        validRecordByDayAdapter.setNewData(orderEntity.getData().getList());

                    }
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(ValidRecordActivity.this, status_error);
            }
        });
    }

    private void initAdapter() {
        rv_list.setLayoutManager(new MyLinearLayoutManager(this));
        validRecordByDayAdapter = new ValidRecordByDayAdapter();
        validRecordByDayAdapter.openLoadAnimation();
        rv_list.setAdapter(validRecordByDayAdapter);
    }


    /**
     * 初始化时间
     */
    private void initDateInfo() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");
        String currentDate = sdf.format(date);
        currentYear = Integer.parseInt(currentDate.split("-")[0]);
        currentMonth = Integer.parseInt(currentDate.split("-")[1]);
        currentDay = Integer.parseInt(currentDate.split("-")[2]);
    }

    private void initCalendarView() {
        SpecialCalendar calendar = new SpecialCalendar();
        boolean isLeapYear = calendar.isLeapYear(currentYear);
        int days = calendar.getDaysOfMonth(isLeapYear, currentMonth);
        int dayOfWeek = calendar.getWeekdayOfMonth(currentYear, currentMonth);
        int todayPosition = currentDay;
        if (dayOfWeek != 7) {
            days = days + dayOfWeek;
            todayPosition += dayOfWeek - 1;
        } else {
            todayPosition -= 1;
        }

        float currentLocation = 1f;
        if (days <= 35) {
            CommonUtils.scale = 0.25f;
            currentLocation = (4 - todayPosition / 7) * CommonUtils.scale;
        } else {
            CommonUtils.scale = 0.2f;
            currentLocation = (5 - todayPosition / 7) * CommonUtils.scale;
        }
        location = currentLocation;

        scrollableLayout.setOnScrollListener(new ScrollableLayout.OnScrollListener() {
            @Override
            public void onScroll(int currentY, int maxY) {
                ViewHelper.setTranslationY(mTopLayout, currentY * location);
            }
        });
        scrollableLayout.getHelper().setCurrentContainer(rv_list);

        gestureDetector = new GestureDetector(this);
        calendarAdapter = new CalendarAdapter(this, getResources(), 0, 0, currentYear, currentMonth, currentDay);
        addGridView();
        gv_calender.setAdapter(calendarAdapter);
    }

    private void addGridView() {

        gv_calender.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return ValidRecordActivity.this.gestureDetector.onTouchEvent(event);
            }
        });

        gv_calender.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            //gridView中的每一个item的点击事件
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                    long arg3) {
                int startPosition = calendarAdapter.getStartPositon();
                int endPosition = calendarAdapter.getEndPosition();
                String scheduleDay;
                String scheduleYear;
                String scheduleMonth;
                location = (float) ((5 - position / 7) * 0.2);
                if (startPosition <= position + 7 && position <= endPosition - 7) {
                    scheduleDay = calendarAdapter.getDateByClickItem(position).split("\\.")[0];  //这一天的阳历
                    scheduleYear = calendarAdapter.getShowYear();
                    scheduleMonth = calendarAdapter.getShowMonth();
                    CommonUtils.zYear = scheduleYear;
                    CommonUtils.zMonth = scheduleMonth;
                    CommonUtils.zDay = scheduleDay;
                    if (CommonUtils.scale == 0.2f) {
                        location = (5 - position / 7) * CommonUtils.scale;
                    } else {
                        location = (4 - position / 7) * CommonUtils.scale;
                    }
                    calendarAdapter.notifyDataSetChanged();

                    tv_date.setText(scheduleYear + "年" + scheduleMonth + "月" + scheduleDay + "日");
                    String start = scheduleYear + "-" + scheduleMonth + "-" + scheduleDay + " " + "00:00:00";
                    String end = scheduleYear + "-" + scheduleMonth + "-" + scheduleDay + " " + "23:59:59";
                    startTime = CommonUtils.dateToStamp(start, "yyyy-MM-dd HH:mm:ss");
                    endTime = CommonUtils.dateToStamp(end, "yyyy-MM-dd HH:mm:ss");
                    getVerificationRecordData();
                }
            }

        });
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {

        return this.gestureDetector.onTouchEvent(event);
    }

    @Override
    public boolean onDown(MotionEvent e) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CommonUtils.zYear = "";
        CommonUtils.zMonth = "";
        CommonUtils.zDay = "";
    }
}
